import { app, shell, BrowserWindow, ipcMain, Menu, net, clipboard, dialog, session } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../build/icon.png?asset'
import { downloadImage, updateServer } from './utils'
import { useGetSystem, useUpdateAccount, useLogin } from './hooks/useGetSystem'
import { checkForUpdates } from './renew' //这是引入的方法
import useJsProxy from './hooks/useJsProxy'
import useExpress from './hooks/useExpress'
import useGetPort from './hooks/useGetPort'
import getCache from './helper/cache'
import useGetJs from './hooks/useGetJs'

// import https from 'https'
// import { exec } from 'child_process'
const isMac = process.platform === 'darwin'
app.commandLine.appendSwitch('disable-site-isolation-trials')
app.commandLine.appendSwitch('disable-features', 'BlockInsecurePrivateNetworkRequests')
// bootstrap()
async function createWindow(port = 36998) {
  const discordProxyJs = await useJsProxy()

  // 让程序自动去找关键词，确保关键词是最新的
  useGetJs(discordProxyJs[0].origin).then((res) => {
    const item = discordProxyJs[0]
    item.keyword = res
    getCache(discordProxyJs)
  })

  // 提前设置缓存
  getCache(discordProxyJs) // 弄到缓存去

  const mainWindow = new BrowserWindow({
    width: 1080,
    height: 750,
    show: false,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      webSecurity: false,
      contextIsolation: false, // false -> 可在渲染进程中使用electron的api，true->需要bridge.js(contextBridge)
      nodeIntegration: true,
      nodeIntegrationInWorker: true,
      experimentalFeatures: true
    }
  })
  if (!is.dev) {
    const menu = Menu.buildFromTemplate([
      {
        label: '寻梦西游',
        submenu: [
          ...(isMac
            ? [
                {
                  label: '寻梦西游',
                  click: function () {
                    // app.quit()
                  }
                }
              ]
            : []),
          {
            label: '退出应用',
            accelerator: 'Command+Q',
            click: function () {
              app.quit()
            }
          },
          {
            label: '退出重登',
            click: function () {
              mainWindow.webContents.send('back-home')
            }
          }
        ]
      },

      {
        label: '编辑',
        submenu: [{ role: 'cut' }, { role: 'copy' }, { role: 'paste' }, { role: 'selectAll' }]
      }
    ])
    Menu.setApplicationMenu(menu)
  }
  mainWindow.on('close', function (event) {
    event.preventDefault()
    mainWindow.webContents.send('get-guild-channel')
  })

  ipcMain.on('set-guild-channel', (event, data) => {
    // 确认操作，通过通讯更新
    const { key, guildId, channelId, label } = data || {}
    if (key && guildId && channelId) {
      const choice = dialog.showMessageBoxSync(mainWindow, {
        type: 'warning',
        cancelId: 2,
        buttons: ['确认', '取消（回自己的服务器，自动绑定）'],
        title: '确认退出',
        message: `请确认当前绑定服务器：【${label}】是您的专属服务器`
      })
      if (choice === 0) {
        if (key && guildId && channelId) {
          updateServer(key, guildId, channelId, () => app.exit())
        }
      }
    } else {
      // 关闭所有窗口
      app.exit()
    }
  })

  // mainWindow.webContents.openDevTools({
  //   mode: 'bottom'
  // })
  // 兼容跨域
  mainWindow.webContents.session.webRequest.onHeadersReceived((d, c) => {
    if (d.responseHeaders['content-security-policy']) {
      d.responseHeaders['content-security-policy'] = [
        "default-src * 'unsafe-inline' 'unsafe-eval'; img-src * data:; media-src *; connect-src *"
      ]
    }
    if (d.responseHeaders['x-frame-options'] || d.responseHeaders['X-Frame-Options']) {
      delete d.responseHeaders['x-frame-options']
      delete d.responseHeaders['X-Frame-Options']
    }
    c({ cancel: false, responseHeaders: d.responseHeaders })
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
    mainWindow.focus()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  ipcMain.on('updateChoice', (event, args) => {
    console.log(JSON.stringify(args), '-----')
  })
  useGetSystem(mainWindow) // 获取配置，给界面送数据
  useUpdateAccount(ipcMain)
  useLogin(ipcMain)

  // 自动更新文件操作
  ipcMain.on('update', () => {
    checkForUpdates(() => {
      dialog.showMessageBox(mainWindow, {
        textWidth: 800,
        buttons: ['确认'],
        title: '更新完成',
        message: '应用更新完成即将重启'
      })
      // 更新完要重启下应用
      // 关闭所有窗口
      app.quit()
      // 重新启动应用程序
      app.relaunch()
    })
  })

  // 监听本地网络操作
  ipcMain.on('getNetworkStatus', (event) => {
    const request = net.request('https://discord.com') // 使用你想要检查的URL
    if (!net.isOnline()) {
      event.reply('networkStatus', { connected: false })
      return
    }
    event.reply('networkStatus', { connected: false })
    console.log(net.isOnline(), '-----online------')
    request.on('response', (response) => {
      console.log(`Status Code: ${response}`)
      if (response.statusCode === 200) {
        console.log('Local network is accessible.')
        event.reply('networkStatus', { connected: true })
        // 让程序自动去找关键词，确保关键词是最新的
        useGetJs(discordProxyJs[0].origin).then((res) => {
          const item = discordProxyJs[0]
          item.keyword = res
          getCache(discordProxyJs)
        })
      } else {
        console.log('Local network is not accessible.')
        event.reply('networkStatus', { connected: false })
      }
    })

    request.on('error', (error) => {
      console.error(`Error: ${error.message}`)
      console.log('Local network is not accessible.')
      event.reply('networkStatus', { connected: false })
    })

    request.end()
  })

  // 登录
  mainWindow.webContents.on('context-menu', async (event, params) => {
    const { x, y, srcURL } = params
    console.log(srcURL, '地址')
    if (!srcURL) return
    const menu = Menu.buildFromTemplate([
      {
        label: '复制图片地址',
        click: function () {
          if (srcURL) {
            clipboard.writeText(srcURL)
            dialog.showMessageBox(mainWindow, {
              type: 'info',
              title: '提示',
              message: '图片地址复制成功'
            })
          }
        }
      },
      {
        label: '保存到本地',
        click: function () {
          if (srcURL) {
            console.log(srcURL, '----地址----')
            dialog
              .showOpenDialog(mainWindow, {
                properties: ['openDirectory']
              })
              .then(async (result) => {
                // 如果用户选择了文件夹，则保存图片到该文件夹中
                if (!result.canceled && result.filePaths.length > 0) {
                  const downloadPath = result.filePaths[0]
                  const res = await downloadImage(srcURL, downloadPath)
                  if (!res) {
                    shell.openExternal(srcURL)
                  }
                  dialog.showMessageBox(mainWindow, {
                    type: 'info',
                    title: '提示',
                    message: res ? '保存成功' : '保存失败，请在浏览器中保存图片'
                  })
                }
              })
          }
        }
      }
    ])

    menu.popup({
      window: mainWindow,
      x,
      y
    })
  })

  session.defaultSession.webRequest.onBeforeRequest((details, callback) => {
    const item = discordProxyJs.find((d) => details.url.indexOf(d.keyword) > -1)
    if (item && details.url.indexOf('localhost:' + port) === -1) {
      // getCache(item)
      callback({
        redirectURL: 'http://localhost:' + port + '/coverjs?url=' + encodeURIComponent(details.url)
      })
      // .replace('https://discord.com', '')
    } else {
      callback({})
    }
  })

  // 进程
  process.on('uncaughtException', (error) => {
    console.log(error.message, '----error---->>>>>')
    // debugger
    // dialog.showErrorBox(
    //   '发生了一个错误',
    //   '发生了一个错误，请重启应用程序。错误详情：' + error.message
    // )
  })
}

app.whenReady().then(async () => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })
  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })

  useGetPort().then((port) => {
    useExpress(port)
    createWindow(port)
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
